#! /bin/bash

set -e

if [ $EUID -ne 0 ]; then
	echo "$(basename $0) must be run as root"
	exit 1
fi

MOUNT_PATH=/tmp/frzr_root

device_list=()
device_output=`lsblk --list -n -o name,model,size,type | grep disk | tr -s ' ' '\t'`

while read -r line; do
	name=/dev/`echo "$line" | cut -f 1`
	model=`echo "$line" | cut -f 2`
	size=`echo "$line" | cut -f 3`
	device_list+=($name)
	device_list+=("$model ($size)")
done <<< "$device_output"

DISK=$(whiptail --nocancel --menu "Choose a disk to install to:" 20 50 5 "${device_list[@]}" 3>&1 1>&2 2>&3)

# Checking for existing installation

REPAIR=false

if (lsblk -o label ${DISK} | grep -q frzr_efi); then
    echo "Existing installation found"

    if (whiptail --yesno --yes-button "Repair" --no-button "Clean" "WARNING: $DISK appears to already have a system installed. Would you like to repair it or do a clean install?\n\nNOTE: A clean install will delete everything on the disk, but a repair install will preserve your user data." 13 70); then
        echo "User chose to do a repair install"
        REPAIR=true
    else
        echo "User chose to do a clean install"
    fi
else
    echo "Existing installation not found"
fi



########## Doing a repair install

if [ "${REPAIR}" == true ]; then

	mkdir -p ${MOUNT_PATH}
	INSTALL_MOUNT=$(fdisk -o Device --list ${DISK} | grep "^${DISK}.*2$")
	BOOT_EFI=$(fdisk -o Device --list ${DISK} | grep "^${DISK}.*1$")
	mount ${INSTALL_MOUNT} ${MOUNT_PATH}
	mount -t vfat ${BOOT_EFI} ${MOUNT_PATH}/boot/
	rm -rf ${MOUNT_PATH}/boot/*
	bootctl --esp-path=${MOUNT_PATH}/boot/ install

	echo "deleting subvolume..."
	btrfs subvolume delete ${MOUNT_PATH}/deployments/* || true
	
	rm -rf ${MOUNT_PATH}/etc/*

	exit 0
fi



########## Doing a fresh install

if ! (whiptail --yesno "WARNING: $DISK will now be formatted. All data on the disk will be lost. Do you wish to proceed?" 10 50); then
	echo "installation aborted"
	exit 1
fi

USERNAME=user

if [ ! -z $1 ]; then
	USERNAME=$1
fi

mkdir -p ${MOUNT_PATH}

# create partition table and create and mount the btrfs filesystem
parted --script ${DISK} \
	mklabel gpt \
	mkpart primary fat32 1MiB 512MiB \
	set 1 esp on \
	mkpart primary 512MiB 100%

PART1=$(fdisk -o Device --list ${DISK} | grep "^${DISK}.*1$")
PART2=$(fdisk -o Device --list ${DISK} | grep "^${DISK}.*2$")

mkfs.btrfs -L frzr_root -f ${PART2}
mount -t btrfs -o nodatacow ${PART2} ${MOUNT_PATH}

btrfs subvolume create ${MOUNT_PATH}/var
btrfs subvolume create ${MOUNT_PATH}/home

mkdir -p ${MOUNT_PATH}/home/${USERNAME}
chown 1000:1000 ${MOUNT_PATH}/home/${USERNAME}

mkdir ${MOUNT_PATH}/boot
mkdir -p ${MOUNT_PATH}/etc
mkdir -p ${MOUNT_PATH}/.etc


# setup boot partition & install bootloader
mkfs.vfat ${PART1}
dosfslabel ${PART1} frzr_efi
mount -t vfat ${PART1} ${MOUNT_PATH}/boot/
bootctl --esp-path=${MOUNT_PATH}/boot/ install
parted ${DISK} set 1 boot on
